#pragma once
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include<cstdio>
#include<unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define PATHNAME "."
#define PROJ_ID 0x66
#define MAX_SIZE 1024
using namespace std;

key_t getKey()
{
    key_t k=ftok(PATHNAME,PROJ_ID);
    if(k<0)
    {
        cerr<<errno<<": "<<strerror(errno)<<endl;
        exit(1);
    }
    return k;
}

int getShmHelper(key_t k,int flags)
{
    int shmid=shmget(k,MAX_SIZE,flags);
    if(shmid<0)
    {
        cerr<<errno<<": "<<strerror(errno)<<endl;
        exit(1);
    }
    return shmid;
}        


int getShm(key_t k)
{
    return getShmHelper(k,IPC_CREAT);
}

int createShm(key_t k)
{
    return getShmHelper(k,IPC_CREAT | 0666);
}

void delShm(int shmid)
{
    if(shmctl(shmid,IPC_RMID,nullptr)==-1)
    {
        cerr<<errno<<": "<<strerror(errno)<<endl;
        exit(1);
    }
    return ;
}

void* attachShm(int shmid)
{
    void* mem=shmat(shmid,nullptr,0);
    if((long long)mem==-1L)
    {
        cerr<<errno<<": "<<strerror(errno)<<endl;
        exit(1);
    }
    return mem;
}

void detachShm(void* start)
{
    if(shmdt(start)==-1)
    {
        cerr<<errno<<": "<<strerror(errno)<<endl;
        exit(1);
    }
    return ;
}